using System;
using System.Linq;
using CloudStorage.Properties;

namespace CloudStorage.API.Messages.Extensions
{
	/// <summary>
	/// Extensions for <see cref="IMessageDataContext"/>
	/// </summary>
	public static class IMessageDataContextExtensions
	{
		/// <summary>
		/// Tries to retrieve a message.
		/// </summary>
		/// <param name="messageDataContext">The <see cref="IMessageDataContext"/> to work on.</param>
		/// <returns>The message retrieved, or null.</returns>
		public static IMessage GetMessage(this IMessageDataContext messageDataContext)
		{
			return messageDataContext.GetMessages(1).FirstOrDefault();
		}

		/// <summary>
		/// Tries to retrieve a message.
		/// </summary>
		/// <param name="messageDataContext">The <see cref="IMessageDataContext"/> to work on.</param>
		/// <param name="visibilityTimeoutInSeconds">The visibility timeout of the retrieved messages in seconds.</param>
		/// <returns>The message retrieved, or null.</returns>
		public static IMessage GetMessage(this IMessageDataContext messageDataContext, int visibilityTimeoutInSeconds)
		{
			return messageDataContext.GetMessages(1, visibilityTimeoutInSeconds).FirstOrDefault();
		}

		/// <summary>
		/// This operation retrieves one messages from the front of the queue, but does not alter the visibility of the message
		/// </summary>
		/// <param name="messageDataContext">The <see cref="IMessageDataContext"/> to work on.</param>
		/// <returns>The message retrieved, or null.</returns>
		public static IMessageInfo PeekMessage(this IMessageDataContext messageDataContext)
		{
			return messageDataContext.PeekMessages(1).FirstOrDefault();
		}

		/// <summary>
		/// True if there is at least one message (at query time) in the current queue.
		/// </summary>
		/// <param name="messageDataContext">The message queue to inspect</param>
		/// <returns>True if there is a message.</returns>
		public static bool HasMessage(this IMessageDataContext messageDataContext)
		{
			return messageDataContext.PeekMessage() != null;
		}

		/// <summary>
		/// Delete an <see cref="IMessage"/> from a Cloud Message Queue
		/// </summary>
		/// <param name="messageDataContext">Data context to delete from</param>
		/// <param name="message"><see cref="IMessage"/> to delete</param>
		/// <exception cref="ArgumentNullException">Expects a valid <see cref="IMessage"/></exception>
		public static void DeleteMessage(this IMessageDataContext messageDataContext, IMessage message)
		{
			if (message == null)
			{
				throw new ArgumentNullException("message", Strings.MissingMessageToDelete);
			}

			messageDataContext.DeleteMessage(message.Id, message.PopReceipt);
		}
	}
}